"use client";
import React, {createContext, useContext, useState} from "react";
import {FilterProps, RecordProps} from "./interface";
import {DataTableSortStatus} from "mantine-datatable";

// 初始化
interface ContextProps {
  PAGE_SIZES: number[];
  EMPTY_FILTER: FilterProps;
  DEFAULT_SORT: DataTableSortStatus<RecordProps>;

  page: number;
  pageSize: number;
  filter: FilterProps;
  fetching: boolean;
  records: RecordProps[];
  totalRecords: number;
  collapse: boolean;
  sortStatus: DataTableSortStatus<RecordProps>;

  setPage: (page: number) => void;
  setPageSize: (size: number) => void;
  setFilter: (filter: FilterProps) => void;
  setFetching: (fetching: boolean) => void;
  setRecords: (records: RecordProps[]) => void;
  setTotalRecords: (totalRecords: number) => void;
  setCollapse: (collapse: boolean) => void;
  setSortStatus: (sortStatus: DataTableSortStatus<RecordProps>) => void;
}

// 创建Context
const IpdTableContext = createContext<ContextProps | null>(null);

// 导出Context组件
export function IpdTableProvider({children}: {children: React.ReactNode}) {
  const PAGE_SIZES = [5, 10, 15];
  const EMPTY_FILTER: FilterProps = {
    type: null,
    name: "",
    oaId: "",
    state: null,
    createdByUserName: "",
    executedByUserName: "",
    reviewedByUserName: "",
  };
  const DEFAULT_SORT: DataTableSortStatus<RecordProps> = {
    columnAccessor: "createdTime",
    direction: "desc",
  };
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(PAGE_SIZES[1]);
  const [filter, setFilter] = useState<FilterProps>(EMPTY_FILTER);
  const [fetching, setFetching] = useState(false);
  const [records, setRecords] = useState<RecordProps[]>([]);
  const [totalRecords, setTotalRecords] = useState(0);
  const [collapse, setCollapse] = useState(true);
  const [sortStatus, setSortStatus] = useState<DataTableSortStatus<RecordProps>>(DEFAULT_SORT);
  return (
    <IpdTableContext.Provider
      value={{
        PAGE_SIZES,
        EMPTY_FILTER,
        DEFAULT_SORT,
        page,
        pageSize,
        filter,
        fetching,
        records,
        totalRecords,
        collapse,
        sortStatus,
        setPage,
        setPageSize,
        setFilter,
        setFetching,
        setRecords,
        setTotalRecords,
        setCollapse,
        setSortStatus,
      }}
    >
      {children}
    </IpdTableContext.Provider>
  );
}

// 导出钩子函数
export const useIpdTableContext = () => {
  const context = useContext(IpdTableContext);
  if (context === null) {
    throw new Error("useIpdTableContext不存在");
  }
  return context; // 返回context
};
